import json
import enc
def get_IP_Address():
  import socket
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  s.connect(('8.8.8.8', 0))
  return s.getsockname()[0]

def get_value(dht, key):
  try:
    return dht[key]
  except KeyError as err:
    return []


def send(dht, user, receiver, message):
  uk = get_private_key(user)
  if not uk:
    print 'sending failed, user private key not found.\n'
    return
  rk = get_public_key(receiver)
  if not rk:
    print 'sending failed, receiver public key not found.\n'
    return
  
  dht_key = str(rk['n']) + ',' + str(rk['e'])
  time_stamp, _, encoded = enc.encode(message, user,
                                      uk['d'], uk['n'], rk['e'], rk['n'])
  dht[dht_key] = get_value(dht, dht_key) + [(time_stamp, encoded)]

def recv(dht, user):
  uk = get_private_key(user)
  if not uk:
    print 'receive failed, user private key not found.\n'
    return
  pk = get_public_key(user)
  if not pk:
    print 'receive failed, user public key not found.\n'
    return
  dht_key = str(pk['n']) + ',' + str(pk['e'])
  msg_list = get_value(dht, dht_key)
  result = []
  for time_stamp, msg in msg_list:
    result.append(enc.decode(msg, uk['d'], uk['n']))
  return result

def get_private_key(user):
  try:
    f = open(user + '.sk')
    json_data = f.read()
    data = json.loads(json_data)
    return {'n': data['n'], 'd': data['d']}
  except:
    return None

def get_public_key(user):
  try:
    f = open('public.pk')
    json_data = f.read()
    data = json.loads(json_data)
    f.close()
    return {'n': data[user]['n'], 'e': data[user]['e']}
  except:
    return None

def generate_key(user):
  from Crypto.PublicKey import RSA
  RSAkey = RSA.generate(1024)
  n=getattr(RSAkey.key, 'n')
  e=getattr(RSAkey.key, 'e')
  d=getattr(RSAkey.key, 'd')
  store_public_key(user, n, e)
  store_private_key(user, n, d)

def store_private_key(user, n, d):
  key_file = user + '.sk'
  import os
  if os.path.isfile(key_file):
    raise 'key file %s exist!' % key_file
  key = {'n': n, 'd': d}
  try:
    f = open(key_file, 'w')
    f.write(json.dumps(key))
    f.close()
    f.read()
  except:
    pass

def store_public_key(user, n, e):
  key = {'n': n, 'e': e}
  try:
    f = open('public.pk')
    json_data = f.read()
    data = json.loads(json_data)
    f.close()
  except:
    data = {}

  try:
    data[user] = key
    f = open('public.pk', 'w')
    f.write(json.dumps(data))
    f.close()
  except:
    pass
